"use client";
import React, { useState } from "react";
import { useDropzone } from "react-dropzone";
import axios from "axios";

interface FileUploadZoneProps {
  onFileUploaded: (pathOnServer: string) => void;
}

export const FileUploadZone: React.FC<FileUploadZoneProps> = ({
  onFileUploaded,
}) => {
  const [selectFile, setSelectFile] = useState<File>();
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadMsg, setUploadMsg] = useState("");

  const onDrop = (acceptedFiles: File[]) => {
    setSelectFile(acceptedFiles[0]);
    setUploadProgress(0);
    setUploadMsg("");
  };

  const handleUpload = async () => {
    if (!selectFile) {
      setUploadMsg("Please select a file to upload.");
      return;
    }
    const formdata = new FormData();
    formdata.append("uploadfile", selectFile);

    try {
      const response = await axios.post(
        "http://172.17.62.81:9988/data/upload",
        formdata,
        {
          headers: { "Content-Type": "multipart/form-data" },
          onUploadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const percentCompleted = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
              );
              setUploadProgress(percentCompleted);
            } else {
              setUploadProgress(100);
            }
          },
        }
      );

      if (response.status === 200) {
        if (response.data.code === 200) {
          setUploadMsg("数据上传成功!");
          onFileUploaded(response.data.data.extracted_folder);
        } else {
          if (response.data.code === 400) {
            setUploadMsg("数据已存在");
          } else {
            setUploadMsg("文件上传失败, 网络错误!");
          }
        }
      }
    } catch (error) {
      console.log(error);
      setUploadMsg("Upload failed. Please try again.");
    }
  };

  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
    multiple: false,
    accept: {
      "application/zip": [".zip"],
    },
  });

  return (
    <div className="flex flex-row items-center gap-4 w-full h-6">
      {/* 文件选择器 */}
      <div
        {...getRootProps()}
        className="relative flex flex-grow border-dashed h-[40px] border-2 rounded-md text-center items-center"
        style={{ cursor: "pointer" }}
      >
        <input {...getInputProps()} />
        <div
          className="absolute flex bg-green-100 h-[40px] items-center justify-center rounded-md opacity-60"
          style={{ width: `${uploadProgress}%` }}
        ></div>
        {selectFile ? (
          <div className="absolute left-4 flex flex-flow items-center justify-center gap-4">
            <p>{selectFile.name}</p>
            {uploadMsg && <p className=" text-red-500">{uploadMsg}</p>}
          </div>
        ) : (
          <p className="absolute left-4">点击选择zip数据文件</p>
        )}
      </div>

      {/* 上传按钮 */}
      <button
        onClick={handleUpload}
        className=" bg-emerald-700 text-white px-4 py-2 rounded"
      >
        Upload
      </button>

      {/* 上传状态消息 */}
    </div>
  );
};
